# exception.py（原文件名保持不变）

from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status


def custom_exception_handler(exc, context):  # 修正函数名去掉多余的
    # 调用默认异常处理器获取初始响应
    response = exception_handler(exc, context)

    # 处理未捕获的异常（response为None的情况）
    if response is None:
        # 这里可以处理500错误或其他未捕获异常
        return Response(
            {"detail": "Server error occurred."},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR,
            headers={'Content-Type': 'application/json'}
        )

    # 自定义401响应
    if response.status_code == status.HTTP_401_UNAUTHORIZED:
        custom_data = {
            "error": {
                "code": "NOT_AUTHENTICATED",
                "message": "Authentication credentials were not provided."
            }
        }
        response.data = custom_data  # 保持数据结构一致性
        # 设置标准化的响应头
        response.headers['Content-Type'] = 'application/json'
        response.headers['WWW-Authenticate'] = 'Bearer realm="api"'

    # 可选：其他状态码的统一处理
    # elif response.status_code == ...:

    return response
